<template>
  <x-dialog
    title="证书"
    :close-on-click-modal="false"
    :show.sync="visible"
    v-if="visible"
    lock-scroll
    append-to-body
    width="1000px"
    :footShow="false"
  >
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-button @click="handleAdd" style="float: right; margin-bottom: 10px" type="primary" v-if="!isDisabled"
        >新增</el-button
      >
      <el-tab-pane label="人员证书" name="first">
        <x-table
          :data-source="tableData"
          size="mini"
          @on-selection-change="handleSelectionChange"
          @on-change="handleTableChange"
          :pagination="pagination"
          :loading="loading"
          :row-key="'id'"
          :height="430"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(item, index) in columnsFirst"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width || 100"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <x-state-cell
                v-if="item.prop === 'state'"
                :stateClass="scope.row['state'] === 0 ? 'danger' : scope.row['state'] ? 'success' : ''"
                :text="selectDictLabel(dictOptions['system.preset'], scope.row['state'])"
              />

              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" :align="'center'" width="200">
            <template #default="scope">
              <more-table-actions
                :permis-list="permissionsActions"
                :action-list="getActions(actions, scope.row)"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </el-tab-pane>
      <el-tab-pane label="特种作业操作证" name="second">
        <x-table
          :data-source="tableData"
          size="mini"
          @on-selection-change="handleSelectionChange"
          @on-change="handleTableChange"
          :pagination="pagination"
          :loading="loading"
          :row-key="'id'"
          :height="430"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(item, index) in columnsSecond"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width || 100"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <x-state-cell
                v-if="item.prop === 'state'"
                :stateClass="scope.row['state'] === 0 ? 'danger' : scope.row['state'] ? 'success' : ''"
                :text="selectDictLabel(dictOptions['system.preset'], scope.row['state'])"
              />

              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" :align="'center'" width="200" v-if="!isDisabled">
            <template #default="scope">
              <more-table-actions
                :permis-list="permissionsActions"
                :action-list="getActions(actions, scope.row)"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </el-tab-pane>
    </el-tabs>
    <x-dialog
      width="50%"
      :title="titleInner"
      :show.sync="innerVisible"
      v-if="innerVisible"
      append-to-body
      :before-close="handleCloseInner"
      @onCancel="handleCloseInner"
      @onSubmit="handleSubmitInner"
      submitText="确定"
    >
      <el-form :model="params" :rules="rules" ref="params" label-position="top">
        <div class="form-components">
          <el-row :gutter="20">
            <x-col :span="8">
              <el-form-item label="证书名称" prop="certName">
                <el-input v-model="params.certName" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8" v-if="activeName === 'first'">
              <el-form-item label="证书等级" prop="certRank">
                <el-input v-model="params.certRank" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8">
              <el-form-item :label="activeName === 'first' ? '证书专业类别' : '作业类别'" prop="certCategory">
                <el-input
                  v-model="params.certCategory"
                  placeholder="请输入"
                  style="width: 100%"
                  maxlength="100"
                ></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8" v-if="activeName === 'second'">
              <el-form-item label="操作项目" prop="certItem">
                <el-input v-model="params.certItem" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8">
              <el-form-item label="证书编号" prop="certCode">
                <el-input v-model="params.certCode" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8" v-if="activeName === 'first'">
              <el-form-item label="注册编号" prop="registrationNo">
                <el-input
                  v-model="params.registrationNo"
                  placeholder="请输入"
                  style="width: 100%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="8">
              <el-form-item label="有效期至" prop="expirationTime">
                <el-date-picker
                  v-model="params.expirationTime"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  default-time="23:59:59"
                  :placeholder="'请输入'"
                >
                </el-date-picker>
              </el-form-item>
            </x-col>
            <x-col :span="8" v-if="activeName === 'second'">
              <el-form-item label="应复审日期" prop="recheckDate">
                <el-date-picker
                  v-model="params.recheckDate"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  default-time="23:59:59"
                  :placeholder="'请选择'"
                >
                </el-date-picker>
              </el-form-item>
            </x-col>
            <x-col :span="8" v-if="activeName === 'second'">
              <el-form-item label="实际复审日期" prop="realityRecheckDate">
                <el-date-picker
                  v-model="params.realityRecheckDate"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  default-time="23:59:59"
                  :placeholder="'请选择'"
                >
                </el-date-picker>
              </el-form-item>
            </x-col>
            <x-col :span="16">
              <el-form-item label="证书验真网址" prop="website">
                <el-input v-model="params.website" placeholder="请输入" style="width: 100%" maxlength="20">
                  <template slot="prepend">Htpp://</template>
                  <template slot="append">.com</template></el-input
                >
              </el-form-item>
            </x-col>
          </el-row>
        </div>
      </el-form>
    </x-dialog>
  </x-dialog>
</template>
<script>
  import {
    TableListMixin,
    QueryDictMixin,
    PermissionsMixin,
    selectDictLabel,
    cloneDeep,
    throttle
  } from '@package/utils'
  import { columnsFirst, columnsSecond, actions } from '@/modules/certification/config/certificateDialog'
  // import { apiMaterialTypeTree } from '@/modules/config/api/materialType'
  import {
    supplierStaffSpecialUrl,
    supplierStaffUrl,
    apiStaffSpecialFindById,
    apiStaffCertFindById,
    apiStaffCertUpdate,
    apiStaffSpecialUpdate,
    apiStaffCertAdd,
    apiStaffSpecialAdd,
    apiStafSpecialfDelete,
    apiStaffCertDelete
  } from '@/modules/certification/api/index.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    components: {},
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    props: {
      title: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: ''
      },
      isDisabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        activeName: 'first',
        listUrl: supplierStaffUrl,
        columnsFirst,
        columnsSecond,
        actions,
        visible: false,
        dictKeys: ['system.preset'],
        searchParams: {
          staffId: ''
        },
        params: {
          certName: '',
          certRank: '',
          certCode: '',
          certCategory: '',
          registrationNo: '',
          expirationTime: '',
          website: '',
          realityRecheckDate: '',
          recheckDate: '',
          certItem: ''
        },
        rules: {
          certName: [
            { required: true, message: '请输入证书名称', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          certCode: [
            { required: true, message: '请输入证书编号', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          registrationNo: [
            { required: true, message: '请输入注册编号', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          expirationTime: [{ required: true, message: '请选择有效期至', trigger: 'change' }]
        },
        innerVisible: false,
        titleInner: '新增',
        loading: false
      }
    },
    computed: {
      getActions() {
        return (actions) => {
          return actions.map((action) => {
            return action
          })
        }
      }
    },
    created() {
      this.initDictConfig()
    },
    methods: {
      selectDictLabel,
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改
            this.getDetail(data.id)
            break
          case 'delete':
            this.handleDel(data.id)
            break
          case 'preview':
            console.log(data)
            // this.preview(data)
            break
          default:
            break
        }
      },
      handleDel(id) {
        this.$confirm('确认删除', '提示', {
          type: 'warning'
        })
          .then(() => {
            if (this.activeName === 'first') {
              apiStaffCertDelete(id).then(() => {
                this.loadData()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              })
            } else {
              apiStafSpecialfDelete(id).then(() => {
                this.loadData()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              })
            }
            this.loadData()
          })
          .catch(() => {})
      },

      preview(row) {
        console.log('row: ', row)
        // const data = {
        //   flowCode: row.flowCode,
        //   flowName: row.flowName,
        //   formType: row.formType,
        //   formConf: row.formData
        // }
        // this.inner = true
        // this.$nextTick(() => {
        //   this.$refs.preview.init(data)
        // })
      },
      handleClick(tab, event) {
        console.log(tab, event)
        this.queryParam = { ...this.searchParams }
        this.listUrl = this.activeName === 'first' ? supplierStaffUrl : supplierStaffSpecialUrl
        this.loadData()
      },

      show(val) {
        this.visible = true
        this.searchParams.staffId = val
        this.queryParam = { ...this.searchParams }
        this.listUrl = this.activeName === 'first' ? supplierStaffUrl : supplierStaffSpecialUrl
        this.loadData()
      },
      handleReset() {
        this.queryParam = { ...this.searchParams }
        this.loadData()
      },
      handleClose() {
        this.selectData = []
        this.visible = false
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      // 弹窗确定
      handleSubmit() {
        if (this.selectData.length) {
          this.$emit('on-confirm', this.selectData)
          this.handleClose()
        } else {
          this.$message.error('请至少选择一条数据点击确定')
        }
      },
      handleAdd() {
        this.titleInner = '新增'
        this.innerVisible = true
      },
      async getDetail(id) {
        this.titleInner = '编辑'
        if (this.activeName === 'first') {
          const { data } = await apiStaffCertFindById(id)
          this.params = Object.assign(this.params, cloneDeep(data))
        } else {
          const { data } = await apiStaffSpecialFindById(id)
          this.params = Object.assign(this.params, cloneDeep(data))
        }
        this.innerVisible = true
      },
      handleCloseInner() {
        this.params = {
          certName: '',
          certRank: '',
          certCode: '',
          certCategory: '',
          registrationNo: '',
          expirationTime: '',
          website: '',
          realityRecheckDate: '',
          recheckDate: '',
          certItem: ''
        }
        this.$refs.params.resetFields()
        this.innerVisible = false
      },
      // 保存
      handleSubmitInner: throttle(function () {
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              staffId: this.searchParams.staffId,
              state: 0,
              ...this.params
            }
            try {
              this.loading = true
              if (this.activeName === 'first') {
                // 人员证书
                const { code } = this.params.id ? await apiStaffCertUpdate(param) : await apiStaffCertAdd(param)
                if (code === EnumApiCode.Success) {
                  this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                }
              } else {
                // 特征证书
                const { code } = this.params.id ? await apiStaffSpecialUpdate(param) : await apiStaffSpecialAdd(param)
                if (code === EnumApiCode.Success) {
                  this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                }
              }
            } finally {
              this.loading = false
              this.handleCloseInner()
              this.queryParam = { ...this.searchParams }
              this.loadData()
            }
          } else {
            return false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .search-btns {
    align-items: flex-end;
    display: flex;
    height: 70px;
  }
</style>
